using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using System.Diagnostics;

namespace GoodStuff
{
    /// <summary>
    /// Bindings: { title, width, height}, bitmap
    /// </summary>
    public class GoodPictureBox : GoodControlBase
    {
        GoodVariable<Bitmap> _variable;
        Graphics _controlGraphics;

        public GoodPictureBox()
        {
        }

        public override void Initialize()
        {
            base.Initialize();

            _variable = (GoodVariable<Bitmap>)ParameterVariable("Variable");
            _variable.ValueChanged += OnVariableChanged;

            Trace.WriteLine("Initializing GoodPictureBox " + _variable.InstanceName);

            int width = Int32.Parse(ParameterText("Width"));
            int height = Int32.Parse(ParameterText("Height"));
            _control = new GroupBox();
            _control.Margin = new Padding(3, 15, 3, 3);
            _control.Size = new Size(width + _control.Margin.Horizontal, height + _control.Margin.Vertical);
            _control.Text = ParameterText("Text");
        }


        protected override void OnVariableChanged(object sender, EventArgs args)
        {
            if (_controlGraphics == null)
            {
                _controlGraphics = _control.CreateGraphics();

                _controlGraphics.SetClip(new Rectangle(
                    _control.Margin.Left,
                    _control.Margin.Top,
                    _control.Size.Width - _control.Margin.Horizontal,
                    _control.Size.Height - _control.Margin.Vertical));
            }

            Bitmap b = _variable.Value;
            _controlGraphics.DrawImage(
                b,
                _controlGraphics.VisibleClipBounds,
                new Rectangle(0, 0, b.Size.Width, b.Size.Height),
                GraphicsUnit.Pixel);
        }

    }
}
